<template>
  <div class="max-w-4xl mx-auto px-4 py-8">
    <div class="bg-white/80 backdrop-blur rounded-xl shadow-lg p-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">每日羊毛</h1>
          <p class="text-sm text-gray-600 mt-1">汇总全网最新羊毛信息，跟着一起赚钱吧！</p>
        </div>
      </div>

      <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-white rounded-md p-3 border">
          <div class="text-sm text-gray-500">置顶标识的羊毛是每天都可以赚钱的哦！</div>
          <div class="mt-2 max-h-80 overflow-auto text-sm">
            <div v-for="k in keys" :key="k" class="px-2 py-2 border-b hover:bg-gray-50 cursor-pointer flex justify-between items-center">
              <div @click="selectKey(k)" class="truncate">{{ k }}</div>
              <div class="text-xs text-gray-400"> <button @click="selectKey(k)" class="text-blue-600">查看</button></div>
            </div>
            <div v-if="!keys.length" class="text-xs text-gray-400">暂无</div>
          </div>
        </div>

        <div class="md:col-span-2">
          <div v-if="loading" class="text-sm text-gray-500">加载中...</div>
          <div v-else-if="!selectedKey" class="text-sm text-gray-500">羊毛列表，点击查看详情</div>
          <div v-else>
            <h2 class="text-lg font-semibold">{{ data.title || selectedKey }}</h2>
            <div class="text-sm text-gray-500 mb-2">key: {{ selectedKey }}</div>
            <div v-if="data.images && data.images.length" class="space-y-2 mb-4">
              <div v-for="(img, idx) in data.images" :key="idx">
                <img :src="img" class="max-w-full rounded shadow" alt="image" />
              </div>
            </div>
            <div v-if="data.content" class="prose max-w-none" v-html="data.content"></div>
            <div v-if="error" class="mt-3 text-sm text-red-600">{{ error }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
declare const useHead: (arg: any) => void
useHead({ title: '每日羊毛 - 生活工具' })

const keys = ref<string[]>([])
const selectedKey = ref('')
const data = ref<any>({})
const loading = ref(false)
const error = ref('')

async function loadKeys() {
  try {
    const res = await fetch('/api/yangmao')
    const json = await res.json()
    if (res.ok) {
      keys.value = json.keys || []
    }
  } catch (e) {
    console.warn(e)
  }
}

async function selectKey(k: string) {
  selectedKey.value = k
  loading.value = true
  error.value = ''
  data.value = {}
  try {
    const res = await fetch(`/api/yangmao?key=${encodeURIComponent(k)}`)
    const json = await res.json()
    if (res.ok) {
      data.value = json.data || {}
    } else {
      error.value = json?.message || '加载失败'
    }
  } catch (e) {
    error.value = String(e)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadKeys()
})
</script>

<style scoped>
.prose img{max-width:100%;}
</style>
